<?php
/**
 * 过户模块逻辑层
 */
namespace AuctionBack\Logic;

use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\Other\Inbox;
use AuctionCore\AuctionOrder\Signature;
use AuctionCore\CarResource\Car;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionCore\Cashier\Payment as CashierPayment;
use AuctionCore\CarDealer\MyAuctioned;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarResource\BreachCar;
use AuctionCore\CarResource\SelfReceiveCar;
use AuctionCore\AuctionOrder\Recheck;
use AuctionCore\AuctionOrder\CarReturn;
use AuctionCore\CarResource\CarModel;
use AuctionCore\Other\Address;
use AuctionCore\CarDealer\TakeMan;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\Account\Back\Employee;
use Think\Log;

class TransferLogic
{

    Protected $autoCheckFields = false;

    public static function addTransferLog($data)
    {
        $info = [
            'order_id' => $data['order_id'],
            'sid' => $data['sid'],
            'result' => 0,
            'createtime' => date('Y-m-d H:i:s')
        ];

        return D('Transfer', 'Model')->add($info);
    }

    /**过户列表组装查询条件**/
    public function makeTransferParams($params)
    {
        $map = array();
        //拍单号
        $orderMap = [];
        if (!empty($params['order_no'])) {
            $orderMap['o.order_no'] = $params['order_no'];
        }
        //车商联系人
        if (!empty($params['contact_person'])) {
            $dealerId = CarDealerLogic::getDealerIdByDealerInfo($params['contact_person']);
            $orderMap['o.success_dealer_id'] = ['eq', $dealerId];
        }
        //车商电话
        if (!empty($params['contact_mobile'])) {
            $dealerId1 = CarDealerLogic::getDealerIdByDealerInfo($params['contact_mobile']);
            if (!empty($orderMap['o.success_dealer_id'])) {
                $orderMap['o.success_dealer_id'] = ['in', [$dealerId1, $dealerId]];
            } else {
                $orderMap['o.success_dealer_id'] = ['eq', $dealerId1];
            }
        }
        $orderMap['o.is_other_channel_deal'] = array('eq', 0);
        $orderIds = $this->getTransferOrder($orderMap);
        if (!empty($orderIds)) {
            $map['order_id'] = ['in', array_column($orderIds, 'order_id')];
        } else {
            $map['order_id'] = ['eq', '-1'];
        }
        $carMap = [];
        if (!$params['auth']) {
            $carOwnerIds = CarOwnerLogic::getCarOwnerInfo(['deliver_id' => $params['emp_id']]);
            if (!empty($carOwnerIds)) {
                $carMap['c.owner_id'] = ['in', array_column($carOwnerIds, 'owner_id')];
            }
        }
        if (!empty($params['bc_city'])) {
            if (is_array($params['bc_city'])) {
                $carMap['c.location_area'] = ['in', $params['bc_city']];
            } else {
                $carMap['c.location_area'] = ['eq', $params['bc_city']];
            }
        }
        //车牌号
        if ($params['car_plate_number']) {
            $where = [];
            $car_plate_number = trim($params['car_plate_number']);
            $car_plate_number_first = mb_substr($car_plate_number, 0, 1, 'UTF8');
            $car_plate_number_last = mb_substr($car_plate_number, 1, 7, 'UTF8');
            $plate_prefix = array_search($car_plate_number_first, C('PLATE_PREFIX'));
            $plate_suffix = substr($car_plate_number, 1);
            $carMap['c.plate_prefix'] = array('eq', $plate_prefix);
            if ($car_plate_number_last) {
                $carMap['c.plate_suffix'] = array('LIKE', $car_plate_number_last . '%');
            }
        }
        $sids = $this->getTransferCars($carMap);
        if (!empty($sids)) {
            $map['sid'] = ['in', array_column($sids, 'sid')];
        } else {
            $map['sid'] = ['eq', '-1'];
        }
        //过户时间
        if (!empty($params['start_time']) || !empty($params['end_time'])) {
            if (empty($params['start_time'])) {
                $map['last_update'] = array("elt", $params['end_time'] . " 23:59:59");
            } elseif (empty($params['end_time'])) {
                $map['last_update'] = array("egt", $params['start_time'] . " 00:00:00");
            } else {
                $map['last_update'] = array(array("egt", $params['start_time'] . " 00:00:00"), array("elt", $params['end_time'] . " 23:59:59 "));
            }
        }
        if ($params['status'] == 1) {
            $map['result'] = array('eq', 0);
        }
        if ($params['status'] == 2) {
            $map['result'] = array('eq', 1);
        }
        if ($params['status'] == 3) {
            $map['result'] = array('eq', 2);
        }
        if ($params['status'] == 4) {
            $map['result'] = array('eq', 3);
        }
        if ($params['status'] == 5) {
            $map['result'] = array('eq', 4);
        }
        return $map;
    }

    /*******/
    private function getTransferOrder($map)
    {
        $prefix = C('DB_PREFIX');
        $info = M('transfer_log')->alias('tl')->field('tl.order_id')
            ->join($prefix . "order as o ON o.order_id = tl.order_id")
            ->where($map)->select();
        return $info;
    }

    /*******/
    private function getTransferCars($map)
    {
        $prefix = C('DB_PREFIX');
        $info = M('transfer_log')->alias('tl')->field('tl.sid')
            ->join($prefix . "car_source as cs ON cs.sid = tl.sid")
            ->join($prefix . "cars as c ON c.car_id = cs.max_car_id")
            ->where($map)->select();
        return $info;
    }

    /**过户列表**/
    public function getTransferList($page = 1, $size = 10, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $size = (int)$size < 1 ? 10 : (int)$size;
        if (!empty($params)) {
            $map = $this->makeTransferParams($params);
        }
        $order = "last_update DESC";
        $total = D('Transfer', 'Model')->relation(true)->where($map)->count();
        $list = D('Transfer', 'Model')->relation(true)->where($map)->limit($size)->page($page)->order($order)->select();

        $cm = new CarModel();
        $addr = new Address();
        $dealer = new Dealer();
        foreach ($list as $key => $value) {
            $list[$key] = $value;
            $list[$key]['order_no'] = $value['Order']['order_no'];
            $list[$key]['is_lock'] = $value['Order']['is_lock'];
            $list[$key]['sno'] = $value['CarSource']['sno'];
            $list[$key]['car_id'] = $value['CarSource']['max_car_id'];
            $carInfo = CarReportLogic::getCarInfo(['car_id' => $value['CarSource']['max_car_id']]);
            $list[$key]['transfer_limit'] = C("TRANSFER_LIMIT." . $carInfo['transfer_limit']);
            $list[$key]['transfer_to_name'] = C("TRANSFER_TO." . $value['transfer_to']);
            $emp_name = Employee::user_info_id($value['emp_id']);
            $list[$key]['emp_name'] = $emp_name['real_name'];
            $brand = $cm->get_model_by_id($carInfo['brand_id'], 'brand');
            $series = $cm->get_model_by_id($carInfo['series_id'], 'series');
            $model = $cm->get_model_by_id($carInfo['model_id']);
            $list[$key]['plate_number'] = C("PLATE_PREFIX." . $carInfo['plate_prefix']) . $carInfo['plate_suffix'];
            $list[$key]['bc_city_name'] = $addr->get_name_by_code($carInfo['location_area']);
            $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];

            $dealerInfo = CarDealerLogic::getDealerInfoByMap(['dealer_id' => $value['Order']['success_dealer_id']]);
            $arr = array();
            $arr['uid'] = $dealer->dealerid_to_uid($dealerInfo['dealer_id']);
            $arr = $dealer->get_contact_mobile_byAntNestfind($arr);
            $list[$key]['contact_person'] = $dealerInfo['contact_person'];
            $list[$key]['contact_mobile'] = $arr['contact_mobile'];

            $carOwnerInfo = CarOwnerLogic::getCarOwnerByMap(['owner_id' => $carInfo['owner_id']]);
            $list[$key]['phone'] = $carOwnerInfo['phone'];
            $list[$key]['seller_name'] = $carOwnerInfo['seller_name'];
            $list[$key]['comefrom'] = $carOwnerInfo['comefrom'];
            $list[$key]['comefrom_url'] = $carOwnerInfo['comefrom_url'];
            if ($params['auth']) {
                $deliver = Employee::user_info_id($carOwnerInfo['deliver_id']);
                $list[$key]['deliver_name'] = $deliver['real_name'];
            }
            //是否显示违约
            $list[$key]['is_again_void'] = true;
            if ($value['Order']['is_lock'] == 1) {
                $list[$key]['is_again_void'] = false;
            }
            //是否显示争议
            $list[$key]['is_show_dispute'] = true;
            if ($value['Order']['is_lock'] == 1) {
                $list[$key]['is_show_dispute'] = false;
            }
            $disInfo = M('dispute')->where(['order_id' => $value['order_id'], 'order_status' => $value['Order']['status'], 'od_type' => 1])->find();
            if ($disInfo) {
                $list[$key]['is_show_dispute'] = false;
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**订单列表组装查询条件**/
    public function makeOrderTransferParams($params)
    {
        $map = array();
        //拍单号
        $orderMap = [];
        if (!empty($params['order_no'])) {
            $orderMap['o.order_no'] = $params['order_no'];
        }
        //车商联系人
        if (!empty($params['contact_person'])) {
            $dealerId = CarDealerLogic::getDealerIdByDealerInfo($params['contact_person']);
            $orderMap['o.success_dealer_id'] = ['eq', $dealerId];
        }
        //车商电话
        if (!empty($params['contact_mobile'])) {
            $dealerId1 = CarDealerLogic::getDealerIdByDealerInfo($params['contact_mobile']);
            if (!empty($orderMap['o.success_dealer_id'])) {
                $orderMap['o.success_dealer_id'] = ['in', [$dealerId1, $dealerId]];
            } else {
                $orderMap['o.success_dealer_id'] = ['eq', $dealerId1];
            }
        }
        $orderMap['o.is_other_channel_deal'] = array('eq', 1);
        $orderIds = $this->getTransferOrder($orderMap);
        if (!empty($orderIds)) {
            $map['order_id'] = ['in', array_column($orderIds, 'order_id')];
        } else {
            $map['order_id'] = ['eq', '-1'];
        }

        $carMap = [];
        if (!$params['auth']) {
            $carOwnerIds = CarOwnerLogic::getCarOwnerInfo(['deliver_id' => $params['emp_id']]);
            $carMap['c.owner_id'] = ['in', array_column($carOwnerIds, 'owner_id')];
        }
        if (!empty($params['bc_city'])) {
            if (is_array($params['bc_city'])) {
                $carMap['c.location_area'] = ['in', $params['bc_city']];
            } else {
                $carMap['c.location_area'] = ['eq', $params['bc_city']];
            }
        }
        //车牌号
        if ($params['car_plate_number']) {
            $where = [];
            $car_plate_number = trim($params['car_plate_number']);
            $car_plate_number_first = mb_substr($car_plate_number, 0, 1, 'UTF8');
            $car_plate_number_last = mb_substr($car_plate_number, 1, 7, 'UTF8');
            $plate_prefix = array_search($car_plate_number_first, C('PLATE_PREFIX'));
            $plate_suffix = substr($car_plate_number, 1);
            $carMap['c.plate_prefix'] = array('eq', $plate_prefix);
            if ($car_plate_number_last) {
                $carMap['c.plate_suffix'] = array('LIKE', $car_plate_number_last . '%');
            }
        }
        $sids = $this->getTransferCars($carMap);
        if (!empty($sids)) {
            $map['sid'] = ['in', array_column($sids, 'sid')];
        } else {
            $map['sid'] = ['eq', '-1'];
        }
        //过户时间
        if (!empty($params['start_time']) || !empty($params['end_time'])) {
            if (empty($params['start_time'])) {
                $map['last_update'] = array("elt", $params['end_time'] . " 23:59:59");
            } elseif (empty($params['end_time'])) {
                $map['last_update'] = array("egt", $params['start_time'] . " 00:00:00");
            } else {
                $map['last_update'] = array(array("egt", $params['start_time'] . " 00:00:00"), array("elt", $params['end_time'] . " 23:59:59 "));
            }
        }
        if ($params['status'] == 1) {
            $map['result'] = array('eq', 0);
        }
        if ($params['status'] == 2) {
            $map['result'] = array('eq', 1);
        }
        if ($params['status'] == 3) {
            $map['result'] = array('eq', 2);
        }
        if ($params['status'] == 4) {
            $map['result'] = array('eq', 3);
        }
        if ($params['status'] == 5) {
            $map['result'] = array('eq', 4);
        }
        return $map;
    }

    /**订单列表**/
    public function getOrderList($page = 1, $size = 10, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $size = (int)$size < 1 ? 10 : (int)$size;
        if (!empty($params)) {
            $map = $this->makeOrderTransferParams($params);
        }
        $order = "createtime DESC";
        $total = D('Transfer', 'Model')->relation(true)->where($map)->count();
        $list = D('Transfer', 'Model')->relation(true)->where($map)->limit($size)->page($page)->order($order)->select();


        $cm = new CarModel();
        $addr = new Address();
        foreach ($list as $key => $value) {
            $list[$key] = $value;
            $list[$key]['order_no'] = $value['Order']['order_no'];
            $list[$key]['sno'] = $value['CarSource']['sno'];
            $list[$key]['car_id'] = $value['CarSource']['max_car_id'];
            $emp_name = Employee::user_info_id($value['emp_id']);
            $list[$key]['emp_name'] = $emp_name['real_name'];
            $carInfo = CarReportLogic::getCarInfo(['car_id' => $value['CarSource']['max_car_id']]);
            $brand = $cm->get_model_by_id($carInfo['brand_id'], 'brand');
            $series = $cm->get_model_by_id($carInfo['series_id'], 'series');
            $model = $cm->get_model_by_id($carInfo['model_id']);
            $list[$key]['plate_number'] = C("PLATE_PREFIX." . $carInfo['plate_prefix']) . $carInfo['plate_suffix'];
            $list[$key]['bc_city_name'] = $addr->get_name_by_code($carInfo['location_area']);
            $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
            $list[$key]['transfer_limit'] = C("TRANSFER_LIMIT." . $carInfo['transfer_limit']);
            $list[$key]['transfer_to_name'] = C("TRANSFER_TO." . $value['transfer_to']);
            if ($value['Order']['refer'] == 1) { //违约车辆
                $breachInfo = BreachCar::getInfoByOtherOrderId($value['Order']['order_id']);
                $list[$key]['contact_person'] = $breachInfo['dealer_name']; //车商联系人
                $list[$key]['contact_mobile'] = $breachInfo['dealer_phone']; //车商电话
            } elseif ($value['Order']['refer'] == 2) { //自收车辆
                $selfCarInfo = SelfReceiveCar::getInfoByOtherOrderId($value['Order']['order_id']);
                $list[$key]['contact_person'] = $selfCarInfo['dealer_name']; //车商联系人
                $list[$key]['contact_mobile'] = $selfCarInfo['dealer_phone']; //车商电话
            }

            $carOwnerInfo = CarOwnerLogic::getCarOwnerByMap(['owner_id' => $carInfo['owner_id']]);
            $list[$key]['phone'] = $carOwnerInfo['phone'];
            $list[$key]['seller_name'] = $carOwnerInfo['seller_name'];
            $list[$key]['comefrom'] = $carOwnerInfo['comefrom'];
            $list[$key]['comefrom_url'] = $carOwnerInfo['comefrom_url'];
            if ($params['auth']) {
                $deliver = Employee::user_info_id($carOwnerInfo['deliver_id']);
                $list[$key]['deliver_name'] = $deliver['real_name'];
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**过户相关信息**/
    public function getTransferInfo($transfer_id)
    {
        $transferInfo = [];
        $transferInfo = $this->getTransferLogInfo($transfer_id);
        $order_id = $transferInfo['order_id'];
        $sid = $transferInfo['sid'];
        //拍单信息
        $o = new OrderLogic($order_id);
        $orderInfo = $o->detail();
        $transferInfo['order_no'] = $orderInfo['order_no'];
        $transferInfo['transfer_fee'] = $orderInfo['transfer_fee'];
        //车辆信息
        $c = new CarSourceLogic($sid);
        $carInfo = $c->detail();
        //报告信息
        $report = new CarReportLogic($carInfo['max_car_id']);
        $reportInfo = $report->detail();
        $transferInfo['car_id'] = $reportInfo['car_id'];
        $transferInfo['car_source'] = $reportInfo['car_source'];
        if ($reportInfo['car_source'] == 1) {
            $carReturnInfo = CarReturn::getCarReturnInfoBySid($sid);
            $transferInfo['invoice'] = $carReturnInfo['invoice'];
            $transferInfo['procedures_upload'] = $carReturnInfo['procedures_upload'];
        } else {
            $transferInfo['invoice'] = "--";
            $transferInfo['procedures_upload'] = "";
        }
        $transferInfo['transfer_limit_id'] = $reportInfo['transfer_limit'];
        $transferInfo['transfer_limit'] = C("TRANSFER_LIMIT." . $reportInfo['transfer_limit']);
        $transferInfo['transfer_type'] = C("TRANSFER_TYPE." . $orderInfo['transfer_type']);
        $transferInfo['transfer_to_name'] = C("TRANSFER_TO." . $transferInfo['transfer_to']);
        //获取车型车牌信息
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($reportInfo['brand_id'], 'brand');
        $series = $cm->get_model_by_id($reportInfo['series_id'], 'series');
        $model = $cm->get_model_by_id($reportInfo['model_id']);
        $transferInfo['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $transferInfo['plate'] = C("PLATE_PREFIX." . $reportInfo['plate_prefix']) . $reportInfo['plate_suffix'];
        $transferInfo['pointer_mileage'] = formatMileage($reportInfo['pointer_mileage']);
        $transferInfo['emission'] = $reportInfo['emission'];
        $transferInfo['car_color'] = $reportInfo['car_color'];
        $transferInfo['first_reg_date'] = $reportInfo['first_reg_date'];
        $transferInfo['composite_state'] = $reportInfo['composite_state'];
        $transferInfo['accident_level'] = $reportInfo['accident_level'];
        $transferInfo['vin'] = $reportInfo['vin'];
        //获取年检有效期
        $procedure = $cm->get_procedure_by_car_id($reportInfo['car_id']);
        $city = new Address();
        $location_area = $city->get_name_by_code($reportInfo['location_area']);
        $transferInfo['location_area'] = $location_area;
        $transferInfo['reg_city'] = $city->get_name_by_code($reportInfo['reg_city']);
        $transferInfo['verify_expiry'] = $procedure['verify_expiry'];
        $transferInfo['com_insure_expiry'] = $procedure['com_insure_expiry'];
        $transferInfo['ill_deduc_point'] = $procedure['ill_deduc_point'];
        $transferInfo['forfeit'] = $procedure['forfeit'];
        //最终成交价
        $transferInfo['last_trans_price'] = \AuctionCore\Other\Price::getLastTransactionPrice($order_id);
        //获取车辆补充说明
        $transferInfo['other_info'] = $cm->getCarOtherInfo($reportInfo['car_id']);
        //车主信息
        $owner = new CarOwnerLogic($reportInfo['owner_id']);
        $ownerInfo = $owner->detail();
        $transferInfo['owner_id'] = $ownerInfo['owner_id'];
        $transferInfo['owner_type'] = $ownerInfo['owner_type'];
        $transferInfo['owner_type_name'] = C('OWNER_TYPE_NAME')[$ownerInfo['owner_type']];
        $transferInfo['seller_name'] = $ownerInfo['seller_name'];
        $transferInfo['phone'] = $ownerInfo['phone'];
        $transferInfo['contact_person'] = $ownerInfo['contact_person'];
        $transferInfo['comefrom'] = $ownerInfo['comefrom'];
        $transferInfo['comefrom_url'] = $ownerInfo['comefrom_url'];
        // 获取评估师信息
        $rec = new Recheck($order_id);
        $checkerInfo = $rec->get_checker_info($ownerInfo['checker_id']);
        $transferInfo['real_name'] = $checkerInfo['real_name'];
        $transferInfo['mobile'] = $checkerInfo['mobile'];
        //车商信息
        $dealer = new CarDealerLogic($orderInfo['success_dealer_id']);
        $dealerInfo = $dealer->detail();
        if ($orderInfo['is_other_channel_deal']) { //如果其他渠道生成的订单就要判断是违约车辆的还是自收车辆的
            if ($orderInfo['refer'] == 1) { //违约车辆
                $breachInfo = BreachCar::getInfoByOtherOrderId($order_id);
                $dealerName = $breachInfo['dealer_name']; //车商联系人
                $dealerPhone = $breachInfo['dealer_phone']; //车商电话
                $takeCarMan = $breachInfo['take_car_man']; //提车人
            } elseif ($orderInfo['refer'] == 2) { //自收车辆
                $selfCarInfo = SelfReceiveCar::getInfoByOtherOrderId($order_id);
                $dealerName = $selfCarInfo['dealer_name']; //车商联系人
                $dealerPhone = $selfCarInfo['dealer_phone']; //车商电话
                $takeCarMan = $selfCarInfo['take_car_man']; //提车人
            }
            $transferInfo['dealer_contact_person'] = $dealerName;
            $transferInfo['dealer_contact_mobile'] = $dealerPhone;
            $transferInfo['take_car_man'] = $takeCarMan;
        } else { //如果不是其他渠道成交的，就从蚁巢那，读取车商联系人信息
            $d = new Dealer();
            $arr['uid'] = $d->dealerid_to_uid($dealerInfo['dealer_id']);
            $arr = $d->get_contact_mobile_byAntNestfind($arr);

            $transferInfo['dealer_contact_person'] = $dealerInfo['contact_person'];
            $transferInfo['dealer_contact_mobile'] = $arr['contact_mobile'];
        }
        //付首款备注 pay_log
        $or = new AuOrder($order_id);
        $pay_log = $or->get_pay_trace_log($reportInfo['car_id']);
        $transferInfo['pay_log_mark'] = $pay_log['remark'];
        //过户跟踪日志
        $followLog = $this->getTransferFollowLog($order_id);
        $transferInfo['followLog'] = $followLog;
        //是否需要显示提成人
        $MyAuctionedInfo = MyAuctioned::detail_by_order_id($order_id);
        $transferInfo['is_show_take_man'] = 1;
        if ($MyAuctionedInfo['man_id'] > 0) {
            $transferInfo['is_show_take_man'] = 0;
            $takeman = new TakeMan();
            $TakeManInfo = $takeman->detail($MyAuctionedInfo['man_id']);
            $transferInfo['take_man_info'] = $TakeManInfo;
        }
        if ($orderInfo['is_other_channel_deal']) {
            $transferInfo['is_show_take_man'] = 0;
        }
        //获取复检信息
        $recheckInfo = RecheckLogic::getDataBySid($sid);
        $procedures_name = Employee::user_info_id($recheckInfo['procedure_checker']);
        $check_name = Employee::user_info_id($recheckInfo['condition_checker']);
        $transferInfo['procedures_name'] = $procedures_name['real_name'];
        $transferInfo['check_name'] = $check_name['real_name'];
        $transferInfo['recheck_time'] = $recheckInfo['recheck_time'];
        $transferInfo['procedures'] = $recheckInfo['procedures'];
        $transferInfo['recheck_remark'] = $recheckInfo['remark'];
        //获取提车人信息(选择用)
        $transferInfo['take_car_men'] = \AuctionCore\CarDealer\Dealer::getTakeCarMan($orderInfo['success_dealer_id']);

        //历史数据兼容
        if (in_array($orderInfo['status'], [11, 13])) {
            //获取订单对应过户图片
            $transfer_img = \AuctionCore\AuctionOrder\AuOrder::getCarTransferImg($order_id);
            $transferInfo['transfer_img'] = $transfer_img;
            //图片的类型
            $img_type = array();
            foreach ($transfer_img as $key => $value) {
                $img_type[] = $value['type'];
            }
            $transferInfo['img_type'] = $img_type;
        }
        return $transferInfo;
    }

    /**过户详情**/
    public function getTransferLogInfo($transfer_id)
    {
        $res = D('Transfer', 'Model')->where('transfer_id =' . $transfer_id)->find();
        return $res;
    }

    /**通过order_id找过户详情**/
    public function getTransferLogInfoByOrderId($order_id)
    {
        $res = D('Transfer', 'Model')->where('order_id =' . $order_id)->find();
        return $res;
    }


    /**过户跟踪日志**/
    private function getTransferFollowLog($order_id)
    {
        $cols = "f.order_id,f.emp_id,f.remark,f.createtime,em.real_name";
        $prefix = C('DB_PREFIX');
        $cond = "f.order_id='" . $order_id . "'";
        $res = M('transfer_follow_log')->alias('f')->field($cols)
            ->join('LEFT JOIN ' . $prefix . "employee as em ON em.emp_id=f.emp_id")
            ->where($cond)->select();
        return $res;
    }

    /**过户数据修改****/
    public static function updateTransferLog($transfer_id, $data)
    {
        $data['last_update'] = date("Y-m-d H:i:s");
        $res = D('Transfer', 'Model')->where('transfer_id =' . $transfer_id)->save($data);
        return $res;
    }

    /**开始过户处理**/
    public function confirmTransfer($data)
    {
        $transferInfo = $this->getTransferLogInfo($data['transfer_id']);
        $o = new OrderLogic($transferInfo['order_id']);
        //开启事务
        M()->startTrans();
        $result = $o->update(array('status' => 10));
        $dataInfo = [];
        $dataInfo['result'] = 1; //过户中
        $dataInfo['transfer_to'] = $data['transfer_to'];
        $dataInfo['deadlinetime'] = $data['transfer_end_time'];
        $dataInfo['startremark'] = $data['remark'];
        $dataInfo['emp_id'] = $data['emp_id'];
        $log_result = self::updateTransferLog($data['transfer_id'], $dataInfo);
        if (!$result || !$log_result) {
            M()->rollback();
            return false;
        }
        $c = new CarSourceLogic($transferInfo['sid']);
        $csData = [];
        $csData['status'] = 402;
        $res_cs = $c->update($csData);
        M()->commit();
        return true;
    }


    /**
     * 通过拍单号得到过户信息
     *
     * @param $orderId 拍单号
     * @return mixed
     */
    public static function getTransferInfoByOrderId($orderId)
    {
        $res = D('Transfer', 'Model')->where('order_id =' . $orderId)->find();
        return $res;
    }

    /**过户中继续跟踪**/
    public function confirmTransferFollow($data)
    {
        $transferInfo = $this->getTransferLogInfo($data['transfer_id']);
        //开启事务
        M()->startTrans();
        $transfer_result = true;
        if ($data['transfer_to'] != $transferInfo['transfer_to'] || $data['deadlinetime'] != $transferInfo['deadlinetime']) {
            $dataInfo = [];
            $dataInfo['transfer_to'] = $data['transfer_to'];
            $dataInfo['deadlinetime'] = $data['deadlinetime'];
            $transfer_result = self::updateTransferLog($data['transfer_id'], $dataInfo);
        }
        $transfer_follow_log = [];
        $transfer_follow_log['order_id'] = $transferInfo['order_id'];
        $transfer_follow_log['emp_id'] = $data['emp_id'];
        $transfer_follow_log['remark'] = $data['track_remark'];
        $transfer_follow_log['createtime'] = date('Y-m-d H:i:s');
        $res = M('transfer_follow_log')->add($transfer_follow_log);
        if (!$res || !$transfer_result) {
            M()->rollback();
            return false;
        } else {
            M()->commit();
            return true;
        }
    }

    /**外迁送档**/
    public function transferSendFile($data)
    {
        $transferInfo = $this->getTransferLogInfo($data['transfer_id']);
        $o = new OrderLogic($transferInfo['order_id']);
        $orderInfo = $o->detail();
        //开启事务
        M()->startTrans();
        $dataInfo = [];
        $dataInfo['result'] = 4; //提档
        $res = true;
        if ($data['man_id'] > 0) {
            $dataInfo['man_id'] = $data['man_id'];
            //提车人数量增加
            $res = TakeMan::updateTakeNum($data['man_id']);
        };
        $dataInfo['emp_id'] = $data['emp_id'];
        $dataInfo['mentiontime'] = $data['mentiontime'];
        $dataInfo['relocationremark'] = $data['mention_remark'];
        $log_result = self::updateTransferLog($data['transfer_id'], $dataInfo);
        if (!$res || !$log_result) {
            M()->rollback();
            return false;
        } else {
            M()->commit();
            return true;
        }
    }

    /**待提档继续跟踪**/
    public function takeTransferFileFollow($data)
    {
        $transferInfo = $this->getTransferLogInfo($data['transfer_id']);
        //开启事务
        M()->startTrans();
        $transfer_result = true;
        if ($data['mentiontime'] != $transferInfo['mentiontime']) {
            $dataInfo = [];
            $dataInfo['mentiontime'] = $data['mentiontime'];
            $transfer_result = self::updateTransferLog($data['transfer_id'], $dataInfo);
        };
        $transfer_follow_log = [];
        $transfer_follow_log['order_id'] = $transferInfo['order_id'];
        $transfer_follow_log['emp_id'] = $data['emp_id'];
        $transfer_follow_log['remark'] = $data['track_remark'];
        $transfer_follow_log['createtime'] = date('Y-m-d H:i:s');
        $res = M('transfer_follow_log')->add($transfer_follow_log);
        if (!$res || !$transfer_result) {
            M()->rollback();
            return false;
        } else {
            M()->commit();
            return true;
        }
    }

    /**
     * 过户成功
     * @param $info
     * @return bool
     */
    public function finishTransfer($info)
    {
        $transferInfo = $this->getTransferLogInfo($info['transfer_id']);
        $o = new OrderLogic($transferInfo['order_id']);
        $orderInfo = $o->detail();
        $now = date("Y-m-d H:i:s");
        //车辆信息
        $c = new CarSourceLogic($transferInfo['sid']);
        $carInfo = $c->detail();
        //报告信息
        $report = new CarReportLogic($carInfo['max_car_id']);
        $reportInfo = $report->detail();

        //开启事务
        M()->startTrans();
        $data = array();
        if ($info['is_show_take_man']) {
            //提车人数量增加
            if ($info['man_id'] > 0) {
                TakeMan::updateTakeNum($info['man_id']);
            }
        }
        //4s店来的车或已付过尾款的个人来源，跳过付尾款流程
        if ($reportInfo['car_source'] == '1') {
            $data['status'] = 13;
            $data['trade_time'] = $now;
            $car_data = array();
            $car_data['car_status'] = 9;
            $car_res = $report->update($car_data);
            if (!$car_res) {
                Log::record("[TransferLogic:finishTransfer]更新报告信息失败，sid {$transferInfo['sid']}", "ERR", true);
                M()->rollback();
                return false;
            }
            //采购单完成
            $resPurchaseOrder = PurchaseOrder::finishBySid($transferInfo['sid']);
            if (!$resPurchaseOrder) {
                Log::record("过户完成:采购单完成失败，sid {$transferInfo['sid']}", "ERR", true);
            }
        } else { //个人流程
            $data['status'] = 11;
            //创建付款单
            $res_pay = $this->createPaymentOrder($reportInfo, $transferInfo['order_id']);
            if (!$res_pay) {
                Log::record("[TransferLogic:finishTransfer]创建付款单失败，sid {$transferInfo['sid']}", "ERR", true);
                M()->rollback();
                return false;
            }
            //更改车辆报告状态 待付尾款
            $res = $report->update(['pay_status' => 3]);
            if ($res === false) {
                Log::record("[TransferLogic:finishTransfer]更改车源报告状态单失败，sid {$transferInfo['sid']}", "ERR", true);
                M()->rollback();
                return false;
            }
        }

        //如果自收车辆则到自收车辆交易成功列表中
        if ($reportInfo['is_self_receive'] == 1) {
            $self_receive_car = new SelfReceiveCar();
            $selfReceiveData = [
                'car_id' => $orderInfo['car_id'],
                'order_id' => $transferInfo['order_id'],
                'trade_price' => $orderInfo['success_price'],
                'status' => 3,
                'deal_time' => $now,
            ];
            $self_receive_car_ret = $self_receive_car->add_self_receive_car($selfReceiveData);
            if (!$self_receive_car_ret) {
                Log::record("[TransferLogic:finishTransfer]自收车辆添加失败，sid {$transferInfo['sid']}", "ERR", true);
                M()->rollback();
                return false;
            }
        }
        $result = $o->update($data);
        if (!$result) {
            Log::record("[TransferLogic:finishTransfer]更新拍单失败，order_id {$transferInfo['order_id']}", "ERR", true);
            M()->rollback();
            return false;
        }
        //更新过户信息
        $dataInfo = [];
        $dataInfo['emp_id'] = $info['emp_id'];
        $dataInfo['result'] = 2;
        $dataInfo['succremark'] = $info['succ_remark'];
        $dataInfo['man_id'] = $info['man_id'] ? $info['man_id'] : 0;
        $log_result = self::updateTransferLog($info['transfer_id'], $dataInfo);
        if (!$log_result) {
            Log::record("[TransferLogic:finishTransfer]更新过户信息失败，sid {$transferInfo['sid']}", "ERR", true);
            M()->rollback();
            return false;
        }
        //找到对应未作废的变更单
        $changeInfo = ChangeOrder::getChangeInfoBySid($transferInfo['sid']);
        $res_change = true;
        if ($changeInfo) {
            //如果变更信息存在，将变更单对应付款状态由-1改成0
            foreach ($changeInfo as $key => $value) {
                $res_change = CashierPayment::changeStatusByMid($value['mid']);
            }
        }
        if (!$res_change) {
            Log::record("[TransferLogic:finishTransfer]更新变更单失败，sid {$transferInfo['sid']}", "ERR", true);
            M()->rollback();
            return false;
        }
        //更新车源为完成状态
        $CarSource = new CarSourceLogic($transferInfo['sid']);
        $csData = [];
        $csData['status'] = 500;
        $res_cs = $CarSource->update($csData);
        if (!$res_cs) {
            Log::record("[TransferLogic:finishTransfer]更新车源状态失败，sid {$transferInfo['sid']}", "ERR", true);
            M()->rollback();
            return false;
        }
        //手续添加
        $addData = [];
        $addData['order_id'] = $transferInfo['order_id'];
        $addData['car_id'] = $orderInfo['car_id'];
        $addData['sid'] = $transferInfo['sid'];
        $addData['emp_id'] = $data['emp_id'];
        $addData['emp_name'] = $data['emp_name'];
        $addData['created_time'] = date('Y-m-d H:i:s');
        $res_add = ProceduresLogic::add($addData);
        if (!$res_add) {
            Log::record("[TransferLogic:finishTransfer]添加手续上传失败，sid {$transferInfo['sid']}", "ERR", true);
            M()->rollback();
            return false;
        }
        //事务提交
        M()->commit();
        //解冻保证金
        AssetCenter::free_all($transferInfo['order_id']);
        //发放抽奖卡卷
        $Raffle = new \AuctionCore\Other\Raffle();
        $Raffle->order_binding_card($transferInfo['order_id'], 2);
        //发送消息
        $oo = new AuOrder($transferInfo['order_id']);
        $cc = new Car($orderInfo['car_id']);
        $uid = $oo->get_uid_by_order();
        $car_name = $cc->get_car_name();
        $content = "【 " . $car_name . " 】拍单编号：" . $orderInfo['order_no'] . "，过户成功。敬请到店收车和取回过户资料。";
        Inbox::sendMessage($uid, '交易成功', $content);
        return true;
    }

    /**
     * 创建付款单
     *
     * @param array $car_detail 车源信息
     * @param int $order_id 拍单ID
     * @return mixed
     */
    private function createPaymentOrder($car_detail, $order_id)
    {
        $sid = $car_detail['sid'];
        $CarReport = new CarReportLogic($car_detail['car_id']);
        $branch_id = $CarReport->getBranchId();
        $purchaseOrder = new PurchaseOrder();
        $purchaseOrderData = $purchaseOrder->viewBySid($sid);
        $purchaseOrderId = $purchaseOrderData['id'];
        $totalAmount = $purchaseOrderData['amount']; //收款总金额
        $paymentData = [];
        $signInfo = Signature::getInfoByOrderId($purchaseOrderData['order_id']);
        $paymentData['bank_name'] = $signInfo['deposit_bank']; //收款银行
        $paymentData['card_no'] = $signInfo['payee_account']; // 收款账号
        $paymentData['account_name'] = $signInfo['payee_name']; //收款人姓名
        $paymentData['pay_type'] = 3; // '采购应付（尾）',
        $paymentData['branch_id'] = $branch_id; // '分公司ID',

        if ($car_detail['three_in_one'] == 1) {//如果三证合一 收50%尾款
            $paymentData['amount'] = $totalAmount / 2; //个人车源 50%首款
        } elseif ($car_detail['three_in_one'] == 2) {
            $paymentData['amount'] = $totalAmount; //个人车源 收100% 全款
        }
        $res6 = $this->generatorPayment($paymentData);//添加付款单
        $res7 = $this->addPaymentRelation($purchaseOrderId, $res6, $paymentData['pay_type']);
        if (!$res6 || !$res7) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 添加付款单
     * @param array $paymentData
     * @return mixed
     */
    private function generatorPayment($paymentData = array())
    {
        $paymentData['pay_way'] = 2;// 转账
        $paymentData['create_time'] = date('Y-m-d H:i:s');//创建时间
        $result = CashierPayment::add($paymentData);
        return $result;
    }

    /**
     * 添加采购单付款关系数据
     *
     * @param int $purchaseOrderId 采购单编号
     * @param int $paymentId 付款单编号
     * @param int $paymentType 付款类型
     * @return mixed
     */
    public function addPaymentRelation($purchaseOrderId, $paymentId, $paymentType)
    {
        $purchaseOrder = new PurchaseOrder();
        return $purchaseOrder->addPaymentAndPurchaseOrderRelation($purchaseOrderId, $paymentId, $paymentType);
    }

}